import formFrame from './formFrame';
export default {
	components: {
		formFrame
	},
	props: {
		value: {
			type: Boolean,
			default: false
		},
		dataId: {
			type: String,
			default: ''
		},
		isSub: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			loading: false,
			visible: this.value,
			formData: {},
			btnLoading: false
		}
	},
	computed: {
		addOrEdit() {
			return !this.dataId;
		},
		formType() {
			if (this.addOrEdit) {
				return 'add'
			} else if (this.isSub) {
				return 'addSub'
			} else {
				return 'edit';
			}
		},
		formTypeText() {
			return this.addOrEdit ? '新增' : '修改';
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) {
				this.$emit('update:isSub', false);
			} else {
				this.getDataDetail();
			}
		}
	},
	methods: {
		//获取数据详情
		async getFormDetail(detailFunc, params) {
			this.loading = true;
			if (this.addOrEdit) {
				this.$nextTick(() => {
					this.$refs['form'].resetFields();
					this.formData = {};
				})
			} else if (this.isSub) {
				this.$nextTick(() => {
					this.$refs['form'].resetFields();
					this.formData = {
						pid: this.dataId
					};
				})
			} else {
				let result = await detailFunc(params).then((res) => res.data);
				if (result.code === '0') {
					this.$refs['form'].resetFields();
					this.formData = this.$detailData(result.data);
				}
			}
			this.loading = false;
		},

		//提交表单
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				await this.submitFormRequest();
				this.btnLoading = false;
			});
		},

		//执行提交方法
		async handleSubmitFunction(params, addFunc, editFunc) {
			let callFunction = eval(this.addOrEdit || this.isSub ? addFunc : editFunc);
			let result = await callFunction(params).then(res => res.data);
			if (result.code === '0') {
				this.visible = false;
				this.$emit('refresh');
				this.$message.success(`${this.formTypeText}${this.formName}成功`);
			}
		}
	}
}